package com.huanxing.cloud.mall.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.core.entity.Result;
import com.huanxing.cloud.mall.api.annotation.HxCheckLogin;
import com.huanxing.cloud.mall.api.service.ICouponUserService;
import com.huanxing.cloud.mall.api.service.IUserInfoService;
import com.huanxing.cloud.mall.api.utils.HxTokenHolder;
import com.huanxing.cloud.mall.common.constant.MallCommonConstants;
import com.huanxing.cloud.mall.common.dto.HxTokenInfo;
import com.huanxing.cloud.mall.common.dto.UserInfoDTO;
import com.huanxing.cloud.mall.common.entity.CouponUser;
import com.huanxing.cloud.mall.common.entity.UserInfo;
import com.huanxing.cloud.mall.common.enums.CouponUserStatusEnum;
import com.huanxing.cloud.miniapp.common.dto.WxUserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 商城用户
 *
 * @author lijx
 * @since 2022/3/1 10:13
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/userinfo")
@Api(value = "userinfo", tags = "商城用户")
public class UserInfoController {

	private final IUserInfoService userInfoService;

	private final RedisTemplate<String, String> redisTemplate;

	private final ICouponUserService couponUserService;

	@ApiOperation(value = "注册用户")
	@PostMapping("/register")
	public Result register(HttpServletRequest request, @RequestBody UserInfo userInfo) {
		if (userInfoService.checkPhone(userInfo.getPhone())) {
			return Result.fail("手机号已存在");
		}
		userInfo.setUserSource(request.getHeader(MallCommonConstants.HEADER_CLIENT_TYPE));
		return Result.success(userInfoService.save(userInfo));
	}

	@ApiOperation(value = "微信小程序更新用户信息")
	@HxCheckLogin
	@PostMapping("/ma/update/info")
	public Result maUpdateInfo(@RequestBody WxUserDTO wxUserDTO) {
		HxTokenInfo hxTokenInfo = HxTokenHolder.getTokenInfo();
		wxUserDTO.setMallUserId(hxTokenInfo.getMallUserId());
		wxUserDTO.setSessionKey(hxTokenInfo.getSessionKey());
		wxUserDTO.setAppId(hxTokenInfo.getAppId());
		wxUserDTO.setWxUserId(hxTokenInfo.getWxUserId());
		UserInfo userInfo = userInfoService.wxMaUpdateInfo(wxUserDTO);
		return Result.success(userInfo);
	}

	@ApiOperation(value = "获取用户信息")
	@HxCheckLogin
	@GetMapping
	public Result getUserInfo() {
		UserInfo userInfo = userInfoService.getById(HxTokenHolder.getMallUserId());
		if (ObjectUtil.isNotNull(userInfo)) {
			userInfo.setCouponCount(couponUserService.count(Wrappers.<CouponUser>lambdaQuery()
				.eq(CouponUser::getUserId, userInfo.getId())
				.eq(CouponUser::getStatus, CouponUserStatusEnum.STATUS_0.getCode())));
		}
		return Result.success(userInfo);
	}

	@ApiOperation(value = "修改用户信息")
	@HxCheckLogin
	@PostMapping("/update/info")
	public Result updateInfo(@RequestBody UserInfo userInfo) {
		userInfo.setPhone(null);
		userInfo.setPassword(null);
		userInfo.setUserSource(null);
		userInfo.setUserGrade(null);
		userInfo.setUserNumber(null);
		userInfo.setAccountBalance(null);
		userInfo.setParentId(null);
		return Result.success(userInfoService.updateById(userInfo));
	}

	@ApiOperation(value = "用户修改手机号")
	@HxCheckLogin
	@PostMapping("/update/phone")
	public Result updatePhone(@RequestBody UserInfoDTO userInfoDTO) {
		String randomStr = userInfoDTO.getPhone();
		String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
		Object codeObj = redisTemplate.opsForValue().get(key);

		if (ObjectUtil.isEmpty(codeObj) || !userInfoDTO.getCode().equals(codeObj)) {
			return Result.fail("验证码不合法");
		}
		String userId = HxTokenHolder.getMallUserId();
		// 查询手机号是否已存在
		long count = userInfoService.count(Wrappers.<UserInfo>lambdaQuery()
			.eq(UserInfo::getPhone, userInfoDTO.getPhone())
			.ne(UserInfo::getId, userId));
		if (count > 0) {
			return Result.fail("手机号已存在");
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setId(userId);
		userInfo.setPhone(userInfoDTO.getPhone());
		return Result.success(userInfoService.updateById(userInfo));
	}

	@ApiOperation(value = "推广人列表")
	@HxCheckLogin
	@GetMapping("/page")
	public Result getPage(Page page, UserInfoDTO userInfoDTO) {
		return Result.success(userInfoService.getPage(page, userInfoDTO));
	}

}
